package com.hongdee.insurance.company.service.impl;

import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.insurance.Common;
import com.hongdee.insurance.company.dao.ITInsuranceDao;
import com.hongdee.insurance.company.entity.TInsuranceCompany;
import com.hongdee.insurance.company.entity.TInsuranceCompanyContractNo;
import com.hongdee.insurance.company.service.ITInsuranceCompanyService;
import com.hongdee.rbac.Constant;
import com.hongdee.rbac.dept.entity.TBcOrgan;
import com.hongdee.rbac.dept.service.ITBcOrganService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by Mr. Xu on 2017/4/24.
 */
@Service
public class TInsuranceCompanyServiceImpl implements ITInsuranceCompanyService {
    @Autowired
    private ITInsuranceDao itInsuranceDao;
    private String tabName = "T_Insurance_Company";
    private String tabEntity = "TInsuranceCompany";
    @Autowired
    private ITBcOrganService organService;

    /**
     * 新增或者修改保险公司
     *
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceCompany saveOrUpdate(TInsuranceCompany data, String uid) throws Exception {
        if (data.getId() == null) {
            //判断保险公司名称是否已经存在
            data.setStatus(Constant.COMPANY);
            if (data.getInsuranceCompanyName() != null) {
                if (existInsuranceCompanyName(data.getInsuranceCompanyName())) {
                    throw new Exception("保险公司名称已经存在！");
                }
            }
            //判断保险代码名称是否已经存在
            if (data.getInsuranceCompanyCode() != null) {
                if (existInsuranceCompanyCode(data.getInsuranceCompanyCode())) {
                    throw new Exception("保险公司代码已经存在！");
                }
            }
            //判断公司名称是否已经存在
            if (data.getCompanyCode() != null) {
                if (existCompanyCode(data.getCompanyCode())) {
                    throw new Exception("公司名称已经存在！");
                }
            }
            //模板选择为空时 默认为0
            if("".equals(data.getTemplet())){
                data.setTemplet("0");
            }
            data.setCreateTime(DateUtils.getNowTime());
            data.setCreateUser(uid);
        } else {//修改
            data.setUpdateTime(DateUtils.getNowTime());
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }
        this.itInsuranceDao.saveOrUpdate(data);
//        this.saveInsuranceCompanyContractNo(data,uid);
        return data ;
    }

    /**
     * 保存历年的合同号信息
     * @param insuranceCompany
     * @param uid
     * @throws Exception
     */
    private void saveInsuranceCompanyContractNo(TInsuranceCompany insuranceCompany,String uid) throws Exception {
        //1、查询当前年 商业险、交强险合同号是否存在
        List<Map<String,Object>> contractNoList=this.itInsuranceDao.list(
                " select * from T_Insurance_Company_CONTRACT_NO where insurance_company_id=? and year=DATE_FORMAT(NOW(),'%Y') " +
                       " and contract_sy_no=? and contract_Jq_no=? ",insuranceCompany.getId(),insuranceCompany.getContractSyNO(),
                insuranceCompany.getContractJqNO());
        //2、存在 则更新即可
        if(contractNoList.size()>0){
            //存在今年的 更新即可
            this.itInsuranceDao.executeSQL("update T_Insurance_Company_CONTRACT_NO set contract_sy_no=?,contract_Jq_no=?," +
                    "contract_len=?,update_time=? where insurance_company_id=?",insuranceCompany.getContractSyNO(),
                    insuranceCompany.getContractJqNO(),insuranceCompany.getContractLen(),DateUtils.getNowTime(),insuranceCompany.getId());
        }else{
            //3、不存在则添加
            TInsuranceCompanyContractNo contractNo=new TInsuranceCompanyContractNo();
            contractNo.setContractSyNO(insuranceCompany.getContractSyNO());
            contractNo.setContractJqNO(insuranceCompany.getContractJqNO());
            contractNo.setContractLen(insuranceCompany.getContractLen());
            contractNo.setInsuranceCompanyId(insuranceCompany.getId());
            contractNo.setYear(DateUtils.formatLongTime(DateUtils.getNowTime(),"yyyy"));
            contractNo.setCreateTime(DateUtils.getNowTime());
            contractNo.setCreateUser(uid);
            contractNo.setUpdateTime(DateUtils.getNowTime());
            this.itInsuranceDao.saveOrUpdate(contractNo);
        }

    }

    private boolean existInsuranceCompanyName(String insuranceCompanyName) throws Exception {
        String sql = "select * from " + tabName + " where status='1' ";
        List param = new ArrayList();
        if (!insuranceCompanyName.isEmpty() && insuranceCompanyName != "") {
            sql += " and insurance_company_name = ? ";
            param.add(insuranceCompanyName);
        }
        Map map = this.itInsuranceDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }

    private boolean existInsuranceCompanyCode(String insuranceCompanyCode) throws Exception {
        String sql = "select * from " + tabName + " where status='1' ";
        List param = new ArrayList();
        if (!insuranceCompanyCode.isEmpty() && insuranceCompanyCode != "") {
            sql += " and insurance_company_code = ? ";
            param.add(insuranceCompanyCode);
        }
        Map map = this.itInsuranceDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }

    private boolean existCompanyCode(String companyCode) throws Exception {
        String sql = "select * from " + tabName + " where status='1' ";
        List param = new ArrayList();
        if (!companyCode.isEmpty() && companyCode != "") {
            sql += " and company_code = ? ";
            param.add(companyCode);
        }
        Map map = this.itInsuranceDao.page(sql, param.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;
    }

    /**
     * 保险公司分页查询
     *
     * @param uid
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map page(String uid, String start, String limit, Map data) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from " + tabName);
        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        //筛选保险公司名称
        if (data.get("insuranceCompanyName") != null && !data.get("insuranceCompanyName").equals("")) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" insurance_company_name like ? ");
            params.add("%" + data.get("insuranceCompanyName") + "%");
        }
        sql.append(" order by sort asc ");
        return this.itInsuranceDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 保险公司停用启用
     *
     * @param id
     * @param status
     * @throws Exception
     */
    @Override
    public void update(String id, String status) throws Exception {
        String hql = "update " + tabEntity + " t set t.status=:status where t.id = :id ";
        Map params = new HashMap();
        params.put("status", status);
        params.put("id", id);
        this.itInsuranceDao.update(hql, params);
    }

    /**
     * 保险公司明细
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择保险公司！");
        }
        String sql = "select * from " + tabName + " where id = ? ";
        return this.itInsuranceDao.info(sql, new Object[]{id});
    }


    /**
     * 根据所在单位的区域信息 以及应用于本单位的佣金来查询公司
     * @return List<Map>
     * @throws Exception
     * @desc 活动的下拉
     * @author 术洪超
     */
    @Override
    public List<Map> combo(String uid,String storeCode) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        Map orginMap=organService.info(companyId);
        String nowDate=DateUtils.formatLongTime(System.currentTimeMillis(),"yyyy-MM-dd");
        StringBuffer sql = new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append(" select * from " + tabName);
        sql.append(" where id in ( ");
        sql.append(" select t.company_id from( " +
                " select * from t_insurance_commission where apply_unit =? ");
        params.add( storeCode);
        sql.append(" UNION ALL " +
                " select * from t_insurance_commission where apply_unit ='0' and area=?  " +
                " )t GROUP BY t.company_id ");
        sql.append(" ) and status='1' ");
        sql.append("order by sort asc");
        params.add(StringUtil.formatEmpty(orginMap.get("oArea")));
        List<Map<String, Object>> mapList = this.itInsuranceDao.list(sql.toString(),params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("id"));
            temp.put("label", map.get("insuranceCompanyName"));
            resList.add(temp);
        }
        return resList;
    }

    /**
     * 获得保险公司详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceCompany getInfo(String id) throws Exception {
        return itInsuranceDao.getInfo(id);
    }

    @Override
    public List<Map<String,Object>> getCompanys() throws Exception {
        String sql="select id,insurance_company_name,insurance_company_code from t_insurance_company order by sort asc";
        List<Map<String,Object>> list=this.itInsuranceDao.list(sql);
        for (Map map:list) {
            String id= StringUtil.formatEmpty(map.get("id"));
            String weekAmount="week_"+id+"_amount";
            map.put("weekAmount",weekAmount);
            String weekPrice="week_"+id+"_price";
            map.put("weekPrice",weekPrice);
            String weekJqAmount="week_"+id+"_jqAmount";
            map.put("weekJqAmount",weekJqAmount);
            String weekJqPrice="week_"+id+"_jqPrice";
            map.put("weekJqPrice",weekJqPrice);
            map.put("weekaddAmount","week_"+id+"_addAmount");
            map.put("weekaddPrice","week_"+id+"_addPrice");
            map.put("weekbackAmount","week_"+id+"_backAmount");
            map.put("weekbackPrice","week_"+id+"_backPrice");
            map.put("weekvvulptPrice","week_"+id+"_vvulptPrice");
            map.put("weekpriceNVVPrice","week_"+id+"_priceNVVPrice");
            map.put("weekdJVVUqPrice","week_"+id+"_dJVVUqPrice");


            map.put("js",id+"_js");
            map.put("jsPrice",id+"_jsPrice");
            map.put("dj",id+"_dj");
            map.put("djPrice",id+"_djPrice");



            String monthAmount="month_"+id+"_amount";
            map.put("monthAmount",monthAmount);
            String monthPrice="month_"+id+"_price";
            map.put("monthPrice",monthPrice);
            String monthJqAmount="month_"+id+"_jqAmount";
            map.put("monthJqAmount",monthJqAmount);
            String monthJqPrice="month_"+id+"_jqPrice";
            map.put("monthJqPrice",monthJqPrice);
            map.put("mountAddAmount","month_"+id+"_addAmount");
            map.put("mountAddPrice","month_"+id+"_addPrice");
            map.put("mountBackAmount","month_"+id+"_backAmount");
            map.put("mountBackPrice","month_"+id+"_backPrice");
            map.put("monthvvulptPrice","month_"+id+"_vvulptPrice");
            map.put("monthpriceNVVPrice","month_"+id+"_priceNVVPrice");
            map.put("monthdJVVUqPrice","month_"+id+"_dJVVUqPrice");
        }
        return list;
    }

    /**
     * 根据出单日期、4s店信息 获得应用于当前4s店所在城市的合同号信息
     * @param insuarnceCompanyId
     * @param outOrderDate
     * @param uid
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String,Object> getInsuranceCompanyInfo(String insuarnceCompanyId,String outOrderDate,String uid,
                                                      String companyId) throws Exception {
        StringBuffer sql=new StringBuffer();
        List<String> params=new ArrayList<>();
        if("".equals(companyId)){
            companyId=TokenUtil.getCompanyId(uid);
        }
        Map<String,Object> organ=organService.info(companyId);
        sql.append("select c.id,c.check_date,c.company_code,c.conntact_phone,c.insurance_company_code,c.insurance_company_name," +
                " c.insurance_start_date,c.insurance_stop_date,c.responsible_person,c.status,c.templet,c.sort," +
                " IFNULL(sy.length_number,'') contract_sy_len,IFNULL(sy.contract_no,'') as contract_sy_no," +
                " IFNULL(jq.length_number,'') contract_jq_len,IFNULL(jq.contract_no,'') as contract_Jq_no from t_insurance_company  c " +
                " left join (" +
                " select * from (" +
                " select * from t_insurance_company_contract where type='sy' and insurance_company_id=? and common_type='0'  " +
                " and city=? and year=DATE_FORMAT(?,'%Y') and area=? and status='1' " +
                " union all" +
                " select * from t_insurance_company_contract where type='sy' and insurance_company_id=? and common_type='1'  " +
                " and year=DATE_FORMAT(?,'%Y') and area=? and status='1' " +
                " ) sytemp limit 1" +
                " ) sy" +
                " on c.id=sy.insurance_company_id");
        params.add(insuarnceCompanyId);
        params.add(StringUtil.formatEmpty(organ.get("oCity")));
        params.add(outOrderDate);
        params.add(StringUtil.formatEmpty(organ.get("oArea")));
        params.add(insuarnceCompanyId);
        params.add(outOrderDate);
        params.add(StringUtil.formatEmpty(organ.get("oArea")));
        sql.append(" left join " +
                " (" +
                " select * from (" +
                " select * from t_insurance_company_contract where type='jq' and insurance_company_id=? and common_type='0'  " +
                " and city=? and year=DATE_FORMAT(?,'%Y') and area=? and status='1' " +
                " union" +
                " select * from t_insurance_company_contract where type='jq' and insurance_company_id=? and common_type='1'  " +
                " and year=DATE_FORMAT(?,'%Y') and area=? and status='1' " +
                " ) jqtemp limit 1" +
                " ) jq" +
                " on c.id=jq.insurance_company_id where c.id=?");
        params.add(insuarnceCompanyId);
        params.add(StringUtil.formatEmpty(organ.get("oCity")));
        params.add(outOrderDate);
        params.add(StringUtil.formatEmpty(organ.get("oArea")));
        params.add(insuarnceCompanyId);
        params.add(outOrderDate);
        params.add(StringUtil.formatEmpty(organ.get("oArea")));
        params.add(insuarnceCompanyId);
        return this.itInsuranceDao.info(sql.toString(),params.toArray());
    }

}
